import { CMEVENTS, Types } from '@amcax/base';
import { ctx2, userEvents } from '@app-cad/module';
import { useEffect, useMemo, useState } from 'react';

export const useParameterLinkedTable = (parameterKey?: string) => {
  const [docObjects, setDocObjects] = useState(ctx2.docMgr.flatDocumentObjects);
  const linkedTable = useMemo(
    () =>
      docObjects.find(({ type, table }) => {
        return (
          type === Types.DESIGN_TABLE &&
          table.active &&
          table.keys.includes(parameterKey) &&
          table.configuration >= 0
        );
      }),
    [docObjects, parameterKey],
  );

  useEffect(() => {
    const abortController = new AbortController();
    userEvents.on(
      CMEVENTS.DOCUMENTS_CHANGE,
      () => setDocObjects(ctx2.docMgr.flatDocumentObjects),
      abortController.signal,
    );

    return () => abortController.abort();
  }, []);

  return linkedTable;
};
